package secendExercise;

import java.util.Arrays;

public class MyArrayList implements IArrayList{
    public int[] elem;
    int usedSize;
    public static final int DEFAULT_SIZE = 5;

    public MyArrayList() {
        elem = new int[DEFAULT_SIZE];
    }


    @Override
    public void display() {
        for (int i = 0; i < usedSize; i++){
            System.out.print(elem[i] + " ");
        }
        System.out.println();
    }

    @Override
    public void add(int data) {
        if (isFull()){
            elem = Arrays.copyOf(elem, 2 * usedSize);
        }
        elem[usedSize++] = data;
    }

    @Override
    public void add(int pos, int data) {
        if (!checkPopLegal(pos)){
            throw new CheckPopLegalException("pos位置："+pos+"不合法！");
        }
        if (isFull()){
            elem = Arrays.copyOf(elem,2 * usedSize);
        }
        for (int i = usedSize-1; i >= pos; i--){
            elem[i+1] = elem[i];
        }
        elem[pos] = data;
        usedSize++;
    }

    @Override
    public boolean contains(int toFind) {
        for (int i = 0; i < usedSize ; i++){
            if (elem[i] == toFind){
                return true;
            }
        }
        return false;
    }

    @Override
    public int indexOf(int toFind) {
        for (int i = 0; i < usedSize ; i++){
            if (elem[i] == toFind){
                return i;
            }
        }
        return -1;
    }

    @Override
    public int get(int pos) {
        if (checkPopLegal(pos))
            return elem[pos];
        else
            throw new CheckPopLegalException("pos位置："+pos+"不合法！");
    }

    @Override
    public boolean isEmpty() {
        return usedSize == 0;
    }

    @Override
    public void set(int pos, int value) {
        if (!checkPopLegal(pos)) throw new CheckPopLegalException("pos位置："+pos+"不合法！");
        elem[pos] = value;
    }

    @Override
    public void remove(int key) {
        if (!contains(key)){
            System.out.println("key值不存在！");
            return;
        }
        int index = indexOf(key);
        for (int i = index + 1; i < usedSize; i++){
            elem[i-1] = elem[i];
        }
        usedSize--;

    }

    @Override
    public int size() {
        return usedSize;
    }

    @Override
    public void clear() {
        elem = null;
        usedSize = 0;
    }
    private boolean isFull(){
        return usedSize == elem.length;
    }
    private boolean checkPopLegal(int pos){
        return pos >= 0 && pos <= usedSize;
    }
}
